package com.service;

import com.dao.TArticleDao;
import com.dao.TTagDao;
import com.entity.TArticle;
import com.entity.TArticleExample;
import com.entity.TTag;
import com.entity.TTagExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by del on 16-5-1.
 */
@Service
public class ArticleService {

    private static Logger LOG = LoggerFactory.getLogger(ArticleService.class);

    @Autowired
    private TArticleDao tArticleDao;

    @Autowired
    private TTagDao tTagDao;

    public Boolean addOrUpdate(TArticle tArticle){
        TArticle result = tArticleDao.selectByAid(tArticle.getAid());
        if (result == null){
            for (TTag tTag : tArticle.getTags()){
                TTagExample tTagExample = new TTagExample();
                tTagExample.createCriteria()
                        .andTitleEqualTo(tArticle.getTitle())
                        .andTagEqualTo(tTag.getTag());
                Boolean isNotExist = tTagDao.selectByExample(tTagExample).isEmpty();
                if (isNotExist) {
                    tTagDao.insert(tTag);
                }
            }
            TArticleExample tArticleExample = new TArticleExample();
            tArticleExample.createCriteria()
                    .andAidEqualTo(tArticle.getAid());
            boolean isSucceed = tArticleDao.insert(tArticle);
            if (isSucceed){
                LOG.info("新增文章成功,title:{},aid:{},url:{}",tArticle.getTitle(),tArticle.getAid(),tArticle.getUrl());
            }
            else {
                LOG.info("新增文章失败,title:{},aid:{},url:{}",tArticle.getTitle(),tArticle.getAid(),tArticle.getUrl());
            }
            return isSucceed;
        }
        else {
//            tArticle.setId(result.getId());
//            boolean isSucceed = null != tArticleDao.update(tArticle);
//            if (isSucceed){
//                LOG.info("更新文章成功,id:{}",result.getId());
//            }
//            else {
//                LOG.info("更新文章失败,id:{}",result.getId());
//            }
//            return isSucceed;
            return true;
        }
    }

    public Boolean remove(Integer id){
        return tArticleDao.delete(id);
    }

    public TArticle modify(TArticle tArticle){
        return tArticleDao.update(tArticle);
    }

    public TArticle get(Integer id){
        return tArticleDao.select(id);
    }

    public Integer getCount(){
        return tArticleDao.selectCount(new TArticleExample());
    }

    public List<TArticle> getAll() {
        return tArticleDao.selectExample(new TArticleExample());
    }

    public List<TArticle> get(Integer page,Integer pageSize){
        return tArticleDao.selectByPage(page,pageSize);
    }

    public TArticle selectNewest(){
        return tArticleDao.selectNewest();
    }
}
